<template>
  <p-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <p-spin :spinning="confirmLoading">
      <p-form :form="form">
        <p-row>
          <p-col :span="24">
            <p-form-item label="程序编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
               <span class="fl">WKE(W)</span>
              <p-input
                style="width: 455px"
                @change="procedureCodeChange"
                v-decorator="[ 'procedureCode', validatorRules.procedureCode]"
                placeholder="请输入程序编码"
              ></p-input>
            </p-form-item>
          </p-col>
          <p-col :span="24">
            <p-form-item label="内部版本 " :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-input
                @change="internalVersionChange"
                v-decorator="[ 'internalVersion', validatorRules.internalVersion]"
                placeholder="请输入内部版本"
              ></p-input>
            </p-form-item>
          </p-col>
          <p-col :span="24">
            <p-form-item label="程序类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                type="list"
                v-decorator="['procedureType', validatorRules.procedureType]"
                :trigger-change="true"
                dictCode="mes_procedure_type"
                placeholder="请选择"
              />
            </p-form-item>
          </p-col>

          <p-col :span="24">
            <p-form-item label="发出时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-date-picker
                @change="onChange"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                valueFormat = "YYYY-MM-DD HH:mm:ss"
                v-decorator="['sendTime', validatorRules.sendTime]"
              />
            </p-form-item>
          </p-col>

          <p-col :span="24">
            <p-form-item label="程序备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-input v-decorator="[ 'remark', validatorRules.remark]" placeholder="请输入标签模板尺寸"></p-input>
            </p-form-item>
          </p-col>
          <p-col :span="24">
            <p-form-item label="程序版本" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-input
                @change="procedureVersionChange"
                v-decorator="[ 'procedureVersion', validatorRules.procedureVersion]"
                placeholder="请输入程序版本"
              ></p-input>
            </p-form-item>
          </p-col>
          <p-col :span="24">
            <p-form-item label="程序名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-input disabled :value="(procedureCode + procedureVersion) || ''" placeholder="请输入程序版本"></p-input>
            </p-form-item>
          </p-col>
          <p-col :span="24">
            <p-form-item label="程序附件" class="must" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p class="download" v-if="isShowDownload">
                <a @click="downloadFile">
                  {{ upFileName }}
                  <p-icon type="download" />下载
                </a>
                <a @click="resetUpload">重新上传</a>
              </p>
              <p-upload
                v-else
                name="file"
                :multiple="false"
                :headers="headers"
                :method="'post'"
                :data="{
                  bucketName: 'mes',
                  expireDate: 0
                }"
                :fileList="fileList"
                accept=".rar, .7z, .zip"
                :action="actionUrl"
                :before-upload="beforeUpload"
                @change="changeFile"
              >
                <a>
                  <p-icon type="import" />导入
                </a>
              </p-upload>
            </p-form-item>
          </p-col>
          <p-col :span="24">
            <p-form-item label="事业部" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                type="list"
                v-decorator="['businessDivision', validatorRules.businessDivision]"
                :trigger-change="true"
                dictCode="mes_business_division"
                placeholder="请选择"
              />
            </p-form-item>
          </p-col>
          <p-col :span="24">
            <p-form-item label="接收部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-tree-select
                @change="pidChange"
                tree-data-simple-mode
                v-decorator="['dptno', validatorRules.dptno]"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                placeholder="请选择父级工序"
                :load-data="onLoadData"
              />
            </p-form-item>
          </p-col>
        </p-row>
      </p-form>
    </p-spin>
  </p-modal>
</template>

<script>
import { httpAction, putAction, api, getAction } from "@/api/manage";
import fSwitch from "@/components/switch";
import { SubmitOnchangMixin } from "@/mixins/SubmitOnchangMixin";
import pick from "lodash.pick";
import { validateDuplicateValue } from "@/utils/util";
import JDictSelectTag from "@/components/dict/JDictSelectTag";

export default {
  name: "ProgramInfoModal",
  mixins: [SubmitOnchangMixin],
  components: {
    JDictSelectTag,
    fSwitch,
  },
  data() {
    return {
      treeData: [
        { id: "00000000", pId: 0, value: "00000000", title: "根目录" },
      ],
      isFileNameRight: false,
      actionUrl: api.test + "/poros-oss/file/upload",
      fileList: [],
      form: this.$form.createForm(this),
      title: "操作",
      width: 800,
      visible: false,
      model: {
        accessoryUrl: "",
      },
      isShowDownload: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      modalState: "edit",
      procedureCode: "",
      internalVersion: "",
      procedureVersion: "",
      upFileName: "",
      confirmLoading: false,
      validatorRules: {
        procedureCode: {
          rules: [{ required: true, message: "请输入程序编码!" }],
        },
        internalVersion: {
          rules: [{ required: true, message: "请输入内部版本!" }],
        },
        procedureType: {
          rules: [{ required: true, message: "请输入程序类型!" }],
        },
        sendTime: {
          rules: [{ required: true, message: "请输入发出时间!" }],
        },
        remark: {
          rules: [{ required: true, message: "请输入程序备注!" }],
        },
        procedureVersion: {
          rules: [{ required: true, message: "请输入程序版本!" }],
        },
        procedureName: {
          rules: [{ required: true, message: "请输入程序名称!" }],
        },
        businessDivision: {
          rules: [{ required: true, message: "请输入事业部!" }],
        },
        dptname: {
          rules: [{ required: true, message: "请输入接收部门!" }],
        },
      },
      url: {
        add: "/mes-craft/mesPeProcedure",
        edit: "/mes-craft/mesPeProcedure",
        childList: "/poros-permission/secOrg/bizList",
      },
    };
  },
  created() {},

  methods: {

    onTimeChangeTest(val){
      console.log(val);
      this.$nextTick( () => {
        console.log(this.TimeTest);
        
      } )
    },

    onLoadData(treeNode) {
      return new Promise((resolve) => {
        const { value } = treeNode.dataRef;
        const pId = value;
        const params = {
          code: value,
        };
        getAction(this.url.childList, params).then((res) => {
          console.log(res);
          if (res.data.length > 0) {
            res.data.forEach((ele) => {
              this.treeData.push({
                id: ele.code,
                title: ele.name,
                value: ele.code,
                pId,
                isLeaf: ele.leaf,
              });
              console.log(ele);
            });

            resolve();
          }
        });
      });
    },

    procedureCodeChange(val) {
      this.procedureCode = document.querySelector(
        "input#procedureCode.poros-input"
      ).value;
    },

    internalVersionChange(val) {
      this.internalVersion = document.querySelector(
        "input#internalVersion.poros-input"
      ).value;
    },

    procedureVersionChange(val) {
      this.procedureVersion = document.querySelector(
        "input#procedureVersion.poros-input"
      ).value;
    },

    changeFile(info) {
      // 只能上传1个文件，且符合要求的文件
      if (this.isFileNameRight) {
        let fileList = [...info.fileList];
        fileList = fileList.slice(-2);
        fileList = fileList.map((file) => {
          if (file.response) {
            file.url = file.response.url;
          }
          return file;
        });
        this.fileList = fileList;
      } else {
        console.log(this.isFileNameRight);
        this.fileList.splice(0);
      }

      // 上传文件
      if (info.file.status !== "uploading") {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === "done") {
        this.$message.success(`${info.file.name} 上传成功`);
        this.model.accessoryUrl = info.file.response.data;
        this.isShowDownload = true;
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} 上传失败.`);
      }
    },

    // 忘记上传前
    beforeUpload(file, fileList) {
      const preName =  "WKE(W)" + this.procedureCode + this.procedureVersion;
      if (
        file.name == preName + ".rar" ||
        file.name == preName + ".7z," ||
        file.name == preName + ".zip,"
      ) {
        this.isFileNameRight = true;
        this.upFileName = file.name;
        return true;
      } else {
        this.isFileNameRight = false;
        this.$message.error(
          "名称须格式为：WKE(W)程序编码+程序版本.rar/.7z/.zip"
        );
        return false;
      }
    },

    
    downloadFile() {
      window.open(
        "https://minio-dev.iiot.hxct.com/mes/1295698610022850562.xls"
      );
    },

    resetUpload() {
      this.isShowDownload = false;
      this.$set(this.model, "accessoryUrl", "");
      this.$set(this.model, "accessoryName", "");
      this.fileList.splice(0);
    },

    add() {
      this.modalState = "add";
      this.edit({});
    },

    edit(record) {
      console.log('record', record);
      
      this.form.resetFields();
      this.model = Object.assign({}, record);
      this.visible = true;
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.model,
            "procedureCode",
            "internalVersion",
            "procedureType",
            "sendTime",
            "remark",
            "accessoryUrl",
            "procedureVersion",
            "procedureName",
            "businessDivision",
            "dptname"
          )
        );
      });
      if (this.modalState == "edit") {
        this.isShowDownload = true;
        const arr = this.model.accessoryUrl.split('.')
        this.upFileName = this.model.accessoryName + "." + arr[arr.length-1]
        this.procedureCode = this.model.procedureCode
        this.procedureVersion = this.model.procedureVersion
        this.internalVersion = this.model.internalVersion
      }
    },
    close() {
      this.$emit("close");
      this.visible = false;
      this.fileList = [];
      this.modalState == "add";
      this.upFileName = ''
      this.internalVersion = ''
      this.procedureCode = ''
      this.procedureVersion = ''
      this.isShowDownload = false
    },
    handleOk() {
      const that = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {

        if (!err) {
          if( !this.isShowDownload){
            this.$message.error('请上传程序附件')
            return 
          }

          that.confirmLoading = true;
          let httpurl = "";
          let method = "";
          this.model.procedureName = this.procedureCode + this.procedureVersion;
          this.model.accessoryName = "WKE(W)" + this.procedureCode + this.procedureVersion;
          let formData = Object.assign(this.model, values);
          this.formData = Object.assign(this.model, values);

          //新增触发
          if (!this.model.id) {
            httpurl += this.url.add;
            method = "post";
            if (this.EnhanceJS.afterAdd) {
              //新增之前
              let Obj = eval(this.EnhanceJS.afterAdd);
              new Obj(this);
            } else {
              console.log("表单提交数据", formData);
              formData.status = 1
              that.modalFrom(httpurl, formData, method);
            }
          } else {
            //编辑触发
            httpurl += this.url.edit;
            method = "put";
            if (this.EnhanceJS.afterEdit) {
              //编辑之前
              let Obj = eval(this.EnhanceJS.afterEdit);
              new Obj(this);
            } else {
              console.log("表单提交数据", formData);
              that.modalFrom(httpurl, formData, method);
            }
          }
        }
      });
    },
    handleCancel() {
      this.close();
    },
    popupCallback(row) {
      this.form.setFieldsValue(
        pick(
          row,
          "procedureCode",
          "internalVersion",
          "procedureType",
          "sendTime",
          "remark",
          "accessoryUrl",
          "procedureVersion",
          "procedureName",
          "businessDivision",
          "dptname"
        )
      );
    },
  },
};
</script>

<style lang="less" scoped>
.download {
  a {
    margin-right: 50px;
  }
}

.must::before {
  position: absolute;
  left: 78px;
  top: 7px;
  display: inline-block;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}

</style>

